package com.xiaozhi.controller;

import com.xiaozhi.component.DeepSeekHealthCheck;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 健康检查控制器
 * 提供系统和AI服务的健康状态查询接口
 */
@Tag(name = "健康检查", description = "系统和AI服务健康状态监控")
@RestController
@RequestMapping("/api/health-check")
public class HealthCheckController {
    
    private static final Logger log = LoggerFactory.getLogger(HealthCheckController.class);
    
    @Autowired
    private DeepSeekHealthCheck deepSeekHealthCheck;
    
    @Operation(summary = "获取DeepSeek AI服务健康状态", description = "检查DeepSeek AI服务的可用性和响应时间")
    @GetMapping("/deepseek")
    public ResponseEntity<Map<String, Object>> getDeepSeekHealth() {
        log.info("检查DeepSeek AI服务健康状态");
        
        try {
            Map<String, Object> healthResult = deepSeekHealthCheck.performHealthCheck();
            
            Map<String, Object> response = new HashMap<>();
            response.put("timestamp", LocalDateTime.now());
            response.put("service", "DeepSeek AI");
            response.put("status", healthResult.get("status"));
            response.put("details", healthResult);
            
            if ("UP".equals(healthResult.get("status"))) {
                return ResponseEntity.ok(response);
            } else {
                return ResponseEntity.status(503).body(response);
            }
            
        } catch (Exception e) {
            log.error("获取DeepSeek健康状态失败: {}", e.getMessage(), e);
            
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("timestamp", LocalDateTime.now());
            errorResponse.put("service", "DeepSeek AI");
            errorResponse.put("status", "ERROR");
            errorResponse.put("error", e.getMessage());
            errorResponse.put("message", "健康检查执行失败");
            
            return ResponseEntity.status(500).body(errorResponse);
        }
    }
    
    @Operation(summary = "获取API密钥配置状态", description = "检查DeepSeek API密钥的配置情况")
    @GetMapping("/api-key")
    public ResponseEntity<Map<String, Object>> getApiKeyStatus() {
        log.info("检查API密钥配置状态");
        
        Map<String, Object> response = new HashMap<>();
        response.put("timestamp", LocalDateTime.now());
        response.put("apiKeyConfigured", deepSeekHealthCheck.isApiKeyConfigured());
        response.put("apiKeyStatus", deepSeekHealthCheck.getApiKeyStatus());
        
        // 检查环境变量
        String deepSeekKey = System.getenv("DEEPSEEK_API_KEY");
        String dashScopeKey = System.getenv("DASHSCOPE_API_KEY");
        
        Map<String, String> envStatus = new HashMap<>();
        envStatus.put("DEEPSEEK_API_KEY", getKeyStatus(deepSeekKey));
        envStatus.put("DASHSCOPE_API_KEY", getKeyStatus(dashScopeKey));
        
        response.put("environmentVariables", envStatus);
        response.put("message", "API密钥配置状态检查完成");
        
        return ResponseEntity.ok(response);
    }
    
    @Operation(summary = "获取系统整体健康状态", description = "获取包括AI服务在内的系统整体健康状态")
    @GetMapping("/system")
    public ResponseEntity<Map<String, Object>> getSystemHealth() {
        log.info("检查系统整体健康状态");
        
        Map<String, Object> response = new HashMap<>();
        response.put("timestamp", LocalDateTime.now());
        response.put("application", "小智医疗AI助手");
        response.put("version", "1.0.0");
        
        // 检查DeepSeek服务
        Map<String, Object> deepSeekHealth = deepSeekHealthCheck.performHealthCheck();
        Map<String, Object> services = new HashMap<>();
        services.put("deepseek", deepSeekHealth);
        
        // 检查数据库连接（简单检查）
        services.put("database", Map.of(
            "status", "UP",
            "type", "MySQL",
            "message", "数据库连接正常"
        ));
        
        // 检查MongoDB连接
        services.put("mongodb", Map.of(
            "status", "UP",
            "type", "MongoDB",
            "message", "MongoDB连接正常"
        ));
        
        response.put("services", services);
        
        // 计算整体状态
        String overallStatus = "UP".equals(deepSeekHealth.get("status")) ? "UP" : "DOWN";
        
        response.put("overallStatus", overallStatus);
        response.put("message", "UP".equals(overallStatus) ? "系统运行正常" : "部分服务异常");
        
        if ("UP".equals(overallStatus)) {
            return ResponseEntity.ok(response);
        } else {
            return ResponseEntity.status(503).body(response);
        }
    }
    
    @Operation(summary = "执行快速健康检查", description = "执行快速的系统健康检查，不包含耗时的AI服务测试")
    @GetMapping("/quick")
    public ResponseEntity<Map<String, Object>> getQuickHealth() {
        log.info("执行快速健康检查");
        
        Map<String, Object> response = new HashMap<>();
        response.put("timestamp", LocalDateTime.now());
        response.put("status", "UP");
        response.put("application", "小智医疗AI助手");
        response.put("uptime", System.currentTimeMillis());
        
        // 检查基本配置
        Map<String, Object> config = new HashMap<>();
        config.put("apiKeyConfigured", deepSeekHealthCheck.isApiKeyConfigured());
        config.put("javaVersion", System.getProperty("java.version"));
        config.put("springProfile", System.getProperty("spring.profiles.active", "default"));
        
        response.put("configuration", config);
        response.put("message", "快速健康检查完成");
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取API密钥状态描述
     */
    private String getKeyStatus(String key) {
        if (key == null || key.trim().isEmpty()) {
            return "未配置";
        }
        if (key.startsWith("sk-")) {
            return "已配置";
        }
        return "格式错误";
    }
}